package com.bj58.ecdata.mailreport.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReflectUtil {
	
	private static Map<Class<?>, ClassInfo> classInfoCache = new HashMap<Class<?>, ClassInfo>();
	
	/**根据字段名 获取GET方法名
	 * @param fieldName
	 * @return
	 */
	public static String getMethodNameByFieldName(String fieldName){
		String result = "";
		char[]  chars  = fieldName.toCharArray();
		char first = chars[0]; //第一个字母
		char second = chars[1]; //第二个字母
		if(Character.isLowerCase(first) && !Character.isLowerCase(second)){ //首字母小写,第二个字母大写
			result =  "get" + fieldName.substring(0);
		}else{
			result =  "get" + fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
		}
			
		return result;
	}
	
	
	private static ClassInfo getClassInfo(Class<?> clazz){
		ClassInfo ci = classInfoCache.get(clazz);
		if(ci == null) {
			try {
				ci = new ClassInfo(clazz);
				classInfoCache.put(clazz, ci);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			
		}
		return ci;
	}
	
	/*
	 * 获得字段对应的set方法
	 */
	public static Method getSetterMethod(Class<?> clazz, Field field) throws Exception {
		ClassInfo ci = getClassInfo(clazz);
		Map<String, Method> mapSetterMethod = ci.getMapSetMethod();
		return mapSetterMethod.get(field.getName());
	}
	
	/*
	 * 获得字段对应的get方法
	 */
	public static Method getGetterMethod(Class<?> clazz, Field field) {
		ClassInfo ci = getClassInfo(clazz);
		Map<String, Method> mapGetterMethod = ci.getMapGetMethod();
		return mapGetterMethod.get(field.getName());
	}
	
	
	/*
	 * 获得所有字段
	 */
	public static List<Field> getAllFields(Class<?> clazz) {
		ClassInfo ci = getClassInfo(clazz);
		Collection<Field> coll = ci.getMapAllDBField().values();
		List<Field> fields = new ArrayList<Field>();
		for(Field f : coll) {
			fields.add(f);
		}
		return fields;
	}
	
	
	public static List<String> getAllFieldsName(Class<?> clazz){
		List<String> fieldsNameList = new ArrayList<String>();
		Field[] fds = clazz.getDeclaredFields();
		for (Field field : fds) {
			fieldsNameList.add(field.getName());
		}
		return fieldsNameList;
	}
}
